<template>
  <!--操作栏：编辑对话框-->
  <el-dialog :model-value="visible" @close="dialogClose" width="50%">
    <!--标题-->
    <template #header>
      <div style="font-size: 18px; color: #409eff; font-weight: bold">修改权限信息</div>
    </template>

    <div class="checkbox_input">
      <input type="checkbox" v-model="selectAll" />
      全选
      <br />
      <label v-for="(item, index) in items" :key="index">
        <input type="checkbox" v-model="forms.permissions" :value="item" />
        {{ item.name }}
      </label>
      <br />
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button type="primary" @click="dialogDepartmentEdit_btn">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
export default {
  name: 'RolesEdit',
  // 介绍父组件的值
  props: {
    visible: Boolean, // 获取dialog是否打开变量
    row: {
      type: [Object, String, Number],
      default: 0
    }
  },
  data() {
    return {
      selectAll: false, // 是否全选
      items: [], // 权限列表
      forms: {
        id: '',
        role: '',
        permissions: [],
      }
    }
  },

  methods: {
    getRolesPermissions() {
      this.$http.get('api/permissions/?page_size=100').then(res => {
        this.items = res.data.data
      })
    },
    // 点击关闭，子组件通知父组件更新属性
    dialogClose() {
      this.$emit('update:visible', false) // 父组件必须使用 v-model
    },

    dialogDepartmentEdit_btn() {
      console.log(this.forms)
      this.$http
        .put('api/roles/' + this.row.id + '/', this.forms)
        .then(res => {
          if (res.data.code == 200) {
            // 反馈请求接口情况
            this.$message.success('修改数据成功')
            // 关闭弹出窗口
            this.dialogClose()
          } else {
            this.$message.info('修改数据失败')
          }
        })
        .catch(error => {
          this.$message.error('服务服务端接口请求错误！' + error)
        })
    }
  },

  // 监听窗口打开，
  watch: {
    visible() {
      if (this.visible) {
        // 关闭窗口不请求
        this.$http.get('api/roles/' + this.row.id + '/').then(res => {
          if (res.data.code == 200) {
            // 权限赋值：从对象中提取ID字段重新赋值
            this.forms.id = res.data.data.id
            this.forms.role = res.data.data.role
            this.forms.permissions = res.data.data.permissions
            
            // 重新渲染
            this.getRolesPermissions()
          }
        })
      }
    },
    // 监听selectAll的变化
    selectAll: function (value) {
      if (value) {
        // 如果全选被勾选，将所有项目加入到selectedItems中
        this.forms.permissions = this.items.slice()
      } else {
        // 如果取消全选，清空selectedItems
        this.forms.permissions = []
      }
    }
  }
}
</script>

<style scoped>
.checkbox_input br {
  margin-bottom: 10px;
}
.checkbox_input label {
  width: 120px;
  margin: 10px;
  display: inline-block;
  vertical-align: middle;
}
</style>
